<template>
  <div class="available-courses">
    <a-alert
      message="可选课程信息"
      description="以下是您当前可以选择的课程列表，请根据个人学习计划合理安排选课。"
      type="info"
      showIcon
      style="margin-bottom: 16px;"
    />
    
    <div class="search-bar">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-input-search
            placeholder="按课程名称、教师搜索"
            @search="handleSearch"
            enterButton
            v-model="searchValue"
          />
        </a-col>
        <a-col :span="12">
          <a-button @click="refresh" style="float: right;">
            <a-icon type="sync" />刷新
          </a-button>
        </a-col>
      </a-row>
    </div>

    <a-table
      :columns="columns"
      :dataSource="filteredCourses"
      rowKey="id"
      :pagination="pagination"
      :loading="loading"
    >
      <span slot="timeLocation" slot-scope="text, record">
        <div>{{ record.time }}</div>
        <div>{{ record.location }}</div>
      </span>

      <span slot="enrollment" slot-scope="text, record">
        {{ record.enrolled }}/{{ record.capacity }}
        <a-progress 
          :percent="Math.round((record.enrolled / record.capacity) * 100)" 
          :status="getProgressStatus(record)"
          size="small"
        />
      </span>

      <span slot="action" slot-scope="text, record">
        <a-button 
          type="primary" 
          size="small"
          @click="handleSelect(record)"
          :disabled="!canSelect(record)"
        >
          选择
        </a-button>
        <a-tooltip v-if="!canSelect(record)" :title="getDisabledReason(record)">
          <a-icon type="question-circle" style="margin-left: 8px" />
        </a-tooltip>
      </span>
    </a-table>
  </div>
</template>

<script>
	// 真实课程数据
	const REAL_COURSES = [{
			id: 'CS101',
			name: '计算机科学导论',
			credit: 3,
			teacher: '李红梅',
			time: 'Mon-1,2',
			location: '理科楼201',
			enrolled: 45,
			capacity: 60,
			type: 'required',
			requirePrerequisite: false
		},
		{
			id: 'CS301',
			name: '数据结构与算法',
			credit: 4,
			teacher: '李红梅',
			time: 'Mon-3,4',
			location: '理科楼202',
			enrolled: 38,
			capacity: 45,
			type: 'required',
			requirePrerequisite: true,
			prerequisite: 'CS101'
		}
	];
const columns = [
  {
    title: '课程编号',
    dataIndex: 'id',
    key: 'id',
    width: 100
  },
  {
    title: '课程名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '学分',
    dataIndex: 'credit',
    key: 'credit',
    width: 80
  },
  {
    title: '任课教师',
    dataIndex: 'teacher',
    key: 'teacher',
    width: 120
  },
  {
    title: '时间/地点',
    key: "timeLocation",
    scopedSlots: { customRender: 'timeLocation' },
    width: 180
  },
  {
    title: '选课人数',
    key: 'enrollment',
    scopedSlots: { customRender: 'enrollment' },
    width: 150
  },
  {
    title: '课程类型',
    dataIndex: 'type',
    key: 'type',
    width: 100,
    customRender: (text) => {
      const typeMap = {
        'required': '必修',
        'elective': '选修',
        'public': '公选'
      };
      return typeMap[text] || text;
    }
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    width: 120
  }
];

export default {
  props: {
    courses: {
      type: Array,
      required: true
    },
    selectedCourses: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      columns,
      filteredCourses: [],
      loading: false,
      searchValue: '',
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50'],
        showTotal: total => `共 ${total} 门可选课程`
      }
    };
  },
  created() {
    this.filterCourses();
  },
  methods: {
	   formatTime(timeStr) {
	        const dayMap = {
	          'Mon': '周一',
	          'Tue': '周二',
	          'Wed': '周三',
	          'Thu': '周四',
	          'Fri': '周五'
	        };
	        const [day, periods] = timeStr.split('-');
	        return `${dayMap[day] || day} 第${periods.split(',').join(',')}节`;
	      },
    filterCourses() {
      let filtered = this.courses;
      
      // 按搜索条件过滤
      if (this.searchValue) {
        const lowerSearch = this.searchValue.toLowerCase();
        filtered = filtered.filter(c => 
          c.name.toLowerCase().includes(lowerSearch) || 
          c.teacher.toLowerCase().includes(lowerSearch)
        );
      }
      
      this.filteredCourses = filtered;
      this.pagination.total = filtered.length;
    },
    
    handleSearch(value) {
      this.searchValue = value;
      this.filterCourses();
    },
    
    refresh() {
      this.loading = true;
      setTimeout(() => {
        this.filterCourses();
        this.loading = false;
      }, 500);
    },
    
    canSelect(course) {
      // 检查是否可以选择该课程
      // 1. 检查是否已选
      if (this.selectedCourses.some(c => c.id === course.id)) {
        return false;
      }
      
      // 2. 检查时间冲突
      const hasConflict = this.selectedCourses.some(selected => {
        return selected.time === course.time;
      });
      if (hasConflict) {
        return false;
      }
      
      // 3. 检查先修课程要求
      if (course.requirePrerequisite) {
        // 这里应该检查学生是否已完成先修课程
        return false;
      }
      
      return true;
    },
    
    getDisabledReason(course) {
      if (this.selectedCourses.some(c => c.id === course.id)) {
        return '您已选择该课程';
      }
      
      const hasConflict = this.selectedCourses.some(selected => {
        return selected.time === course.time;
      });
      if (hasConflict) {
        return '时间冲突';
      }
      
      if (course.requirePrerequisite) {
        return `需要先修课程: ${course.prerequisite}`;
      }
      
      return '不可选';
    },
    
    getProgressStatus(course) {
      const percent = (course.enrolled / course.capacity) * 100;
      if (percent >= 90) {
        return 'exception';
      } else if (percent >= 70) {
        return 'active';
      }
      return 'normal';
    },
    handleSelect(course) {
      this.$confirm({
              title: '确认选择该课程吗?',
              content: `课程名称: ${course.name}\n任课教师: ${course.teacher}\n上课时间: ${this.formatTime(course.time)}`,
              onOk: () => {
                this.selectedCourses.push(course);
                const courseIndex = this.courses.findIndex(c => c.id === course.id);
                if (courseIndex !== -1) {
                  this.courses[courseIndex].enrolled += 1;
                  this.filterCourses();
                }
                this.$message.success(`成功选择课程: ${course.name}`);
              }
            });
    }
  }
};
</script>

<style scoped>
.available-courses {
 padding: 20px;
 padding-top: 0;
}
.search-bar {
  margin-bottom: 16px;
}
</style>